package com.parktech.sun.domain.service.downloadcenter.impl;

import com.parktech.sun.domain.model.downloadcenter.ResourceFile;
import com.parktech.sun.domain.model.downloadcenter.ResourceType;
import com.parktech.sun.domain.repository.Page;
import com.parktech.sun.domain.repository.downloadcenter.ResourceFileRepository;
import com.parktech.sun.domain.service.downloadcenter.ResourceFileService;
import com.parktech.sun.domain.service.impl.BaseServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Property;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * User: Think
 * Date: 11-1-23
 * Time: 下午11:51
 */
@Service
public class ResourceFileServiceImpl extends BaseServiceImpl<ResourceFile> implements ResourceFileService {

    private ResourceFileRepository resourceFileRepository;

    @Autowired
    public ResourceFileServiceImpl(ResourceFileRepository resourceFileRepository) {
        super(resourceFileRepository);
        this.resourceFileRepository = resourceFileRepository;
    }

    public Page search(String name, Integer publishStatus, Page page) {

        Criteria criteria = resourceFileRepository.createCriteria();

        if (StringUtils.isNotEmpty(name)) {
            criteria.add(Property.forName("name").like(name, MatchMode.ANYWHERE));
        }

        if (publishStatus != null && publishStatus != -1) {
            criteria.add(Property.forName("publishStatus").eq(publishStatus));
        }

        criteria.addOrder(Order.desc("orderCode"));
        criteria.addOrder(Order.desc("publishDate"));
        criteria.addOrder(Order.desc("modifyTime"));

        return resourceFileRepository.page(criteria, page);
    }

    public Page searchType(String name, Page page) {

        Criteria criteria = resourceFileRepository.createCriteria(ResourceType.class);

        if (StringUtils.isNotEmpty(name)) {
            criteria.add(Property.forName("name").like(name, MatchMode.ANYWHERE));
        }

        return resourceFileRepository.page(criteria, page);
    }

    public ResourceType getTypeById(Long resourceTypeId) {
        return resourceFileRepository.getTypeById(resourceTypeId);
    }

    public void saveOrUpdateType(ResourceType resourceType) {
        resourceFileRepository.saveOrUpdateType(resourceType);
    }

    public List<ResourceFile> listAll() {

        Criteria criteria = resourceFileRepository.createCriteria();
        criteria.add(Property.forName("publishStatus").eq(1));
        criteria.addOrder(Order.desc("orderCode"));
        criteria.addOrder(Order.desc("publishDate"));
        criteria.addOrder(Order.desc("modifyTime"));

        return criteria.list();
    }
}
